package com.css.fxfzypg.modules.maps.controller;

import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.repository.SettingSeismicRepository;
import com.css.fxfzypg.modules.SettingSeismic.service.IntensityRelationService;
import com.css.fxfzypg.modules.maps.entity.InfluencefliedFilesEntity;
import com.css.fxfzypg.modules.maps.queryParams.InfluencefliedQueryParams;
import com.css.fxfzypg.modules.maps.service.InfluencefliedMapService;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.resultupload.repository.ResultTotalRepository;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zyt
 * @create 2022-11-29
 * 导入地震影响场
 */
@RestController
@RequestMapping("/influencefliedImport")
@Slf4j
public class InfluencefliedController {

    @Resource
    IntensityRelationService intensityRelationService;
    @Resource
    PreAssessResultService preAssessResultService;

    @Resource
    private PreAssessTaskRepository preAssessTaskRepository;

    @Resource
    InfluencefliedMapService influencefliedMapService;//地图使用

    @Resource
    SettingSeismicRepository settingSeismicRepository;

    @Resource
    ResultTotalRepository resultTotalRepository;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    /*zyt修改--start*/
    /**
     * 全查询  模糊查询未设定条件
     * @param request
     * @param queryParams
     * @return
     */
    @GetMapping("/getAllInfluencefliedData")
    public RestResponse getAllInfluencefliedData(HttpServletRequest request, InfluencefliedQueryParams queryParams){

        RestResponse restResponse = null;
        try{
            //查询条件
            String taskId = request.getParameter("taskId");
            String fileUuid = request.getParameter("fileUuid");
            String uuid = request.getParameter("uuid");
            queryParams.setTaskId(taskId);
            queryParams.setFileuuid(fileUuid);
            queryParams.setUuid(uuid);
            restResponse = RestResponse.succeed(influencefliedMapService.getAllData(queryParams));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }
    /**
     * 根据ID查询数据
     */
    @GetMapping("/getInfluencefliedDataById/{id}")
    public RestResponse getInfluencefliedDataById(@PathVariable("id") String id){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(influencefliedMapService.getDataById(id));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }
    /**
     * 根据文件ids逻辑删除文件及物理删除相关数据
     */
    @PostMapping("/delInfluencefliedFileData/{taskId}/{ids}")
    public RestResponse delInfluencefliedFileData(@PathVariable("taskId") String taskId,@PathVariable("ids") List<String> ids) {
        RestResponse restResponse = null;
        try{
            String userID = PlatformSessionContext.getUserID();
            influencefliedMapService.deleteFileData(taskId,null,ids,userID);
            restResponse = RestResponse.succeed("删除成功");
        }catch (Exception e){
            log.error("删除失败!",e);
            restResponse = RestResponse.fail("删除失败!");
        }
        return restResponse;
    }
    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/influencefliedUpload")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, InfluencefliedQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        //任务ID
        String taskId = queryParams.getTaskId();
        String detailsId = queryParams.getDetailsId();//setting_seismic_details明细表id
        if (PlatformObjectUtils.isEmpty(taskId) || PlatformObjectUtils.isEmpty(detailsId)) {
            return RestResponse.fail("上传失败，缺少任务参数");
        }
        //查询任务
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);
        String taskName = preAssessTaskEntity.getTaskName();
        //查询设定地震明细
        SettingSeismicDetails settingSeismicDetails = settingSeismicRepository.getSettingSeismicDetailsById(detailsId);
        if(settingSeismicDetails==null){
            return RestResponse.fail("上传失败，未查到设定地震");
        }
        String tempName = "序号"+settingSeismicDetails.getFaultNum()
                +"_"+settingSeismicDetails.getLongitude()+"_"+settingSeismicDetails.getLatitude()
                +"_"+settingSeismicDetails.getEarthquakeLevel()+"_"+settingSeismicDetails.getAngle();

        //查询全部导入影响场标识数量
        int importFlagCount = influencefliedMapService.countAllImportFlag(taskId);
        if(importFlagCount>0){
            //根据任务ID和detailsId逻辑删除导入影响场文件及物理删除相关数据
            influencefliedMapService.deleteFileDataByTaskIdDetailsId(taskId,detailsId);
        }else{
            //逻辑删除导入影响场文件及物理删除相关数据
            //influencefliedMapService.deleteFileDataByTaskId(taskId);
            //删除与任务关联的影响场
            intensityRelationService.deleteSsiByTaskId(taskId);
            intensityRelationService.deleteSipByTaskId(taskId);
            preAssessResultService.deleteSeiCapdistribution(taskId);
            //删除评估结果
            resultTotalRepository.delResultTotalByTaskId(taskId, null);
            resultTotalRepository.delResultDetailsEntityByTaskId(taskId, null);

            SeismicIntensityRelation entity1 = intensityRelationService.getByTaskId(taskId);
            if (PlatformObjectUtils.isEmpty(entity1)) {
                entity1 = new SeismicIntensityRelation();
                entity1.setTaskId(taskId);
                entity1.setModel1Type("3");//导入影响场
                entity1.setButton1_status1("0");
                entity1.setButton2_status1("0");
                entity1.setButton2_status2("0");
                entity1.setButton2_status3("0");
                entity1.setButton3_status1("0");
                entity1.setButton3_status2("0");
                entity1.setButton4_status1("0");
                entity1.setButton4_status2("0");
                entity1.setButton5_status1("0");
                entity1.setButton6_status1("0");
                entity1.setButton7_status1("0");
                entity1.setButton8_status1("0");
                entity1.setButton8_status2("0");
                entity1.setButton8_status3("0");
                entity1.setButton9_status1("0");
                intensityRelationService.saveSeismicIntensityRelation(entity1);
            } else {
                entity1.setModel1Type("3");//导入影响场
                entity1.setButton1_status1("0");
                entity1.setButton2_status1("0");
                entity1.setButton2_status2("0");
                entity1.setButton2_status3("0");
                entity1.setButton3_status1("0");
                entity1.setButton3_status2("0");
                entity1.setButton4_status1("0");
                entity1.setButton4_status2("0");
                entity1.setButton5_status1("0");
                entity1.setButton6_status1("0");
                entity1.setButton7_status1("0");
                entity1.setButton8_status1("0");
                entity1.setButton8_status2("0");
                entity1.setButton8_status3("0");
                entity1.setButton9_status1("0");
                intensityRelationService.updateSeismicIntensityRelation(entity1);
            }
        }

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String gdbFileName = "";//gdb文件名
        String jxfilename = "";//shp文件名
        String dbffilename = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        //判断是否为GDB文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            if (oldFileName.equals("gdb")) {//是否存在gdb文件
                String fName = "新建文件地理数据库";
                String postfix = ".gdb";
                String prefix = "导入地震影响场_";
                String district = taskName+"_"+tempName;//任务名称
                gdbFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                break;
            }
        }

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
                newFileName = gdbFileName + "/"+oldFileName;
            }else {//SHP文件
                // 上传后文件名
                String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
                String prefix = "导入地震影响场_";
                String district = taskName+"_"+tempName;//任务名称
                newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                    jxfilename = newFileName;
                }
                if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                    dbffilename = newFileName;
                }
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                //File _file = new File(uploadPath + newFileName);
                //FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            //returnMsg.append(oldFileName);
            //returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename+gdbFileName);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
            resultMsg = gdbFileName;//返回GDB文件名
            System.out.println(new Date()+"-----------3.开始importGDBFile");
            //resMsg = qhRiskLevelMapService.checkGDBFiles(uploadPath + gdbFileName, province, city, area);
            System.out.println(new Date()+"-----------4.结束importGDBFile");
            if (resMsg.indexOf("spatialReferenceError") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据.");
        }else{//SHP文件
            System.out.println(new Date()+"-----------3.开始importShapeFile");
            resMsg = influencefliedMapService.checkSHPFiles(taskId,detailsId,uploadPath + jxfilename, formatDate, userID);
            System.out.println(new Date()+"-----------4.结束importShapeFile");
        }
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "字段值存在空值, 请对照字段说明检查数据的正确性.");
        //if (resMsg.indexOf("PointIsNotInDistrict") != -1) return RestResponse.succeed("存在没有位于 【" + province + city + area + "】 行政边界的数据, 请检查数据的正确性.");
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        //if(resMsg.indexOf("PointOverlapError")!=-1) return RestResponse.succeed("上传文件中数据存在空间位置重叠, 请检查数据的正确性.");
        if (resMsg.indexOf("pgaFormatError") != -1) return RestResponse.succeed("PGA不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("pgvFormatError") != -1) return RestResponse.succeed("PGV不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("pgv_vs30FormatError") != -1) return RestResponse.succeed("PGV_vs30不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("intensityFormatError") != -1) return RestResponse.succeed("烈度不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("intensityNumError") != -1) return RestResponse.succeed("文件中无烈度6-10（Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ）的数据，请检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    /**
     * 根据任务id获取所有明细数据
     */
    @GetMapping("/getSettingSeismicDetailsByTaskId/{taskId}")
    public RestResponse getSettingSeismicDetailsByTaskId(@PathVariable("taskId") String taskId) {
        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(settingSeismicRepository.getSettingSeismicDetailsByTaskId(taskId));
        }catch (Exception e){
            log.error("查询失败!",e);
            restResponse = RestResponse.fail("查询失败!");
        }
        return restResponse;
    }
    /*zyt修改--end*/
}
